﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FacadeApi.Extension
{
    public class TokenValidFilter : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.Request.Headers["Referer"].Equals("http://localhost:5000/swagger/index.html")) return;

            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                DeviceToken(filterContext);
            }
            else
            {
                UIDToken(filterContext);
            }
        }

        public void DeviceToken(ActionExecutingContext filterContext)
        {
            var DeviceID = (string)filterContext.HttpContext.Request.Headers["DeviceID"];
            var Token = (string)filterContext.HttpContext.Request.Headers["vToken"];

            if (string.IsNullOrWhiteSpace(Token))
            {
                ContentResult contentResult = new ContentResult();
                contentResult.Content = "DeviceToken Is Missing!";
                contentResult.StatusCode = 403;

                filterContext.Result = contentResult;
                return;
            }

            var r = TokenManager.ValidDeviceToken(DeviceID, Token);

            if (!r)
            {
                ContentResult contentResult = new ContentResult();
                contentResult.Content = "DeviceToken Verification failed!";
                contentResult.StatusCode = 403;

                filterContext.Result = contentResult;
            }
        }
        public void UIDToken(ActionExecutingContext filterContext)
        {
            var info = filterContext.ActionDescriptor.AttributeRouteInfo;

            var uid = filterContext.HttpContext.User.Claims.First(i => i.Type == "ID").Value;

            var Token = (string)filterContext.HttpContext.Request.Headers["vToken"];
            if (string.IsNullOrWhiteSpace(Token))
            {
                ContentResult contentResult = new ContentResult();
                contentResult.Content = "UserToken Is Missing!";
                contentResult.StatusCode = 403;

                filterContext.Result = contentResult;
                return;
            }

            var userID = int.Parse(uid);

            var r = TokenManager.ValidToken(userID, Token);

            if (!r)
            {
                ContentResult contentResult = new ContentResult();
                contentResult.Content = "UserToken Verification failed!";
                contentResult.StatusCode = 403;

                filterContext.Result = contentResult;
                return;
            }

        }
    }
}
